package cn.xdmnb.cloud.blog.plugin.web.exception;

import cn.xdmnb.cloud.blog.core.dict.ResultCode;
import cn.xdmnb.cloud.blog.core.model.ResultMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author yukai
 * @since 2023年01月05日 22:42
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class})
    public ResultMsg<Void> handler(Throwable ex){
        if (ex instanceof MethodArgumentNotValidException){
            log.error("参数错误： {}" , ex.getMessage(), ex);
            return ResultMsg.<Void>resultFail(ResultCode.PARAMETER_FAIL.getCode(), ResultCode.PARAMETER_FAIL.getMsg());
        }
        if (ex instanceof ServiceException){
            ServiceException serviceException = (ServiceException) ex;
            log.error("业务异常: {}", serviceException.getMessage(), ex);
            return ResultMsg.<Void>resultFail(serviceException.getCode(),serviceException.getMessage());
        }
        log.error("系统出现了异常：{}",ex.getMessage(), ex);
        return ResultMsg.<Void>resultFail();
    }

}
